#include "mytcpserver.h"

MyTcpServer::MyTcpServer()
{

}

MyTcpServer &MyTcpServer::getInstance()
{
    static MyTcpServer instance;
    return instance;
}

void MyTcpServer::incomingConnection(qintptr handle)
{
    qDebug() << "新客户端连接";
    MyTcpSocket* pTcpSocket = new MyTcpSocket;
    pTcpSocket->setSocketDescriptor(handle);
    m_tcpSocketList.append(pTcpSocket);
    connect(pTcpSocket, &MyTcpSocket::OffLine, this, &MyTcpServer::deleteSocket);
}

void MyTcpServer::deleteSocket(MyTcpSocket *mysocket)
{
   m_tcpSocketList.removeOne(mysocket);//移除
   mysocket->deleteLater();//延迟删除
   mysocket = NULL;

   foreach (MyTcpSocket* pSocket, m_tcpSocketList) {//打印的是剩余的
       qDebug() << "deleteSocket: " << pSocket->m_strName;
   }
}

void MyTcpServer::resend(char *tarName, PDU *pdu)
{
    for(int i = 0; i < m_tcpSocketList.size(); i++)//遍历socket链表
    {
        if(tarName == m_tcpSocketList.at(i)->m_strName)//判断名字是否为当前遍历到的socket
        {
            m_tcpSocketList.at(i)->write((char*)pdu, pdu->uiPDULen);//发送，这里不能直接调用writePDU函数，否则直接就释放了
        }
    }
}
